<template>
  <el-dialog
    title="工作日设置"
    v-model="dialogVisible"
    :modal="true"
    :appendToBody="true"
    width="40%"
    :close-on-click-modal="false"
    top="5vh"
    class="report-text-form"
    @close="handleClose()"
    @open="handleOpen()"
  >
    <div class="dia-sub">
      <div>
        <span>{{ weekData.year }}年</span>
        <span>{{ weekData.month }}月</span>
        <span>{{ weekData.day }}日</span>
        <span class="week">{{ weekData.week }}</span>
        <br />
        <span>{{ baseData.join("-") }}</span>
      </div>
    </div>
    <el-form
      label-position="right"
      ref="ruleForm"
      label-width="200px"
      v-loading="saveloading"
    >
      <template v-if="teamList && teamList.length">
        <el-form-item
          v-for="item in teamList"
          :key="item.id"
          :label="item.workTime"
        >
          <el-radio-group v-model="item.produceStatus">
            <el-radio label="ON">工作</el-radio>
            <el-radio label="OFF">休息</el-radio>
          </el-radio-group>
        </el-form-item>
      </template>
    </el-form>
    <div class="tips" v-if="baseData.length != 4">
      设置成功后，将生效于其下所有
      <span v-if="baseData.length == 1">工段、产线、工艺段</span>
      <span v-else-if="baseData.length == 2">产线、工艺段</span>
      <span v-else-if="baseData.length == 3">工艺段</span>
    </div>

    <!-- <span slot="footer" class="dialog-footer">
      <el-button @click="$emit('submit-success', false)">取 消</el-button>
      <el-button type="primary" :loading="saveloading" @click="handleSubmit"
        >确 定</el-button
      >
    </span> -->
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" :loading="saveloading" @click="handleSubmit"
          >确 定</el-button
        >
        <el-button @click="$emit('submit-success', false)">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script>
import { listShift } from "@/api/base/plan/shiftMgt/shiftMaintenance";
import { changeLineProduceStatus } from "@/api/base/plan/shiftMgt/userChange";
import { getDept } from "@/api/system/dept";
import { SHIFT_MODE } from "../config";
export default {
  props: {
    value: {
      type: Boolean,
      default: false,
    },
    weekData: {
      type: Object,
      default: () => {},
    },
    baseData: {
      type: Object,
      default: () => {},
    },
    weekdayItem: {
      type: Object,
      default: () => {},
    },
    baseDataCode: {
      type: Object,
      default: () => {},
    },
    baseDataId: {
      type: Object,
      default: () => {},
    },
  },
  data() {
    return {
      pager: {
        total: 0,
        pageNum: 1,
        pageSize: 100,
      },
      teamList: [],
      saveloading: false,
      shiftMode: "",
    };
  },
  computed: {
    dialogVisible: {
      set(val) {
        this.$emit("update:visible", val);
      },
      get() {
        return this.visible;
      },
    },
    // dialogVisible: {
    //   set(val) {
    //     this.$emit("input", val);
    //   },
    //   get() {
    //     return this.value;
    //   },
    // },
  },
  methods: {
    handleClose() {
      this.saveloading = false;
      this.resetFormData();
    },
    getFactoryDetail() {
      console.log(
        this.weekData,
        this.baseData,
        this.weekdayItem,
        this.baseDataCode,
        this.baseDataId,
        "why"
      );
      getDept(this.baseDataId[0]).then((res) => {
        let classesMode = 2;
        if (res.data.classesMode) {
          classesMode = res.data.classesMode;
        }
        const modeList = SHIFT_MODE.filter((el) => el.value == classesMode);
        this.teamList = modeList[0].children;
        this.teamList.forEach((ele) => {
          ele.workTime = ele.scheduleName;
          ele.produceStatus = `ON`;
        });
      });
    },
    handleOpen() {
      this.resetFormData();
      this.teamList = JSON.parse(
        JSON.stringify(this.weekdayItem?.classesDutyList || [])
      );
      console.log(
        this.teamList,
        "======this.teamList======this.teamList==this.teamList"
      );
      if (!this.teamList?.length) {
        //没有配置工作日
        this.getFactoryDetail();
      } else {
        this.teamList.forEach((item) => {
          //获取班次
          if (item?.workshopDutyInfoList?.length) {
            item.workshopDutyInfoList.forEach((ele) => {
              //获取车间安排
              if (ele?.lineDutyInfoList?.length) {
                //获取车间下面产线安排
                // if (!ele.lineDutyInfoList.some(this.isExistRest)) {
                //   //所有产线都是休息日
                //   // this.$set(ele, "produceStatus"/, "OFF");
                //   ele.produceStatus = "OFF";
                // } else {
                //   // this.$set(ele, "produceStatus", "ON");
                //   ele.produceStatus = "ON";
                // }
                ele.lineDutyInfoList.forEach(info=>{
                  if (!info.sectionDutyInfoDtoList.some(this.isExistRest)) {
                    //所有产线都是休息日
                    // this.$set(ele, "produceStatus"/, "OFF");
                    ele.produceStatus = "OFF";
                  } else {
                    // this.$set(ele, "produceStatus", "ON");
                    ele.produceStatus = "ON";
                  }
                })
                
              } else {
                // this.$set(ele, "produceStatus", "ON");
                ele.produceStatus = "ON";
              }
            });

            if (
              item.workshopDutyInfoList.every(this.isExisStatus) &&
              !item.workshopDutyInfoList.some(this.isExistRest)
            ) {
              //所有s车间存在produceStatus，并且所有车间都是休息日
              // this.$set(item, "produceStatus", "OFF");
              item.produceStatus = "OFF";
            } else {
              // this.$set(item, "produceStatus", "ON");
              item.produceStatus = "ON";
            }
          } else {
            // this.$set(item, "produceStatus", "ON");
            item.produceStatus = "ON";
          }

          this.$nextTick(() => {
            // this.$set(
            //   item,
            //   "workTime",
            //   `${item.classesName}(${item.startTime}-${item.endTime})`
            // );
            item.workTime = `${item.scheduleName}`;
            // this.$set(item, "id", item.classesId);
            item.id = item.classesId;
          });
        });
      }
    },

    isExistRest(value, index, ar) {
      if (value?.produceStatus == "ON") {
        return true;
      } else {
        return false;
      }
    },

    isExisStatus(value, index, ar) {
      if (value?.produceStatus) {
        return true;
      } else {
        return false;
      }
    },

    getList() {
      this.saveloading = true;
      this.single = null;
      const { pageNum, pageSize } = this.pager;
      const params = {
        query: {
          searchValue: "",
        },
        pageNum,
        pageSize,
      };
      getDept(params)
        .then((response) => {
          if (response.code == 200 && response?.rows?.length) {
            this.teamList = response.rows || [];

            this.teamList.forEach((ele) => {
              this.$nextTick(() => {
                this.$set(ele, "workTime", `${ele.scheduleName}`);
                this.$set(ele, "produceStatus", "ON");
              });
            });
          } else {
            this.teamList = [];
          }
          this.saveloading = false;
        })
        .catch(() => {
          this.teamList = [];
          this.saveloading = false;
        });
    },

    handleSubmit() {
      this.saveloading = true;
      // const { factory, workshopId, lineId } = this.baseData;
      const factory = this.baseDataCode[0] || "";
      const workshopCode = this.baseDataCode[1] || "";
      const productLine = this.baseDataCode[2] || "";
      const sectionCode = this.baseDataCode[3] || "";
      const { year, month, day } = this.weekData;
      const parmas = {
        factory,
        workshopCode,
        productLine,
        sectionCode,
        yearStr: year,
        monthStr: month,
        dayNo: day,
        classesProduceStatusList: this.teamList?.length
          ? this.teamList.map((ele) => {
              return {
                // classesId: ele?.id,
                scheduleName: ele?.workTime,
                // startTime: ele?.startTime,
                // endTime: ele?.endTime,
                produceStatus: ele?.produceStatus,
              };
            })
          : [],
      };
      changeLineProduceStatus(parmas)
        .then((res) => {
          if (res.code == 200) {
            this.saveloading = false;
            this.dialogVisible = false;
            console.log("sasaas");
            this.$modal.msgSuccess("操作成功");
            this.$emit("submit-success", true);
          } else {
            this.$modal.msgError("操作失败");
          }
        })
        .catch(() => {
          this.$modal.msgError("操作失败");
          this.saveloading = false;
        });
    },

    resetFormData() {
      this.$refs.ruleForm?.resetFields();
      this.teamList = [];
    },
  },
};
</script>
<style lang="scss" scoped>
.report-text-form {
  .el-form {
    margin-top: 20px;
  }
  .dia-sub {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 24px;
    font-size: 15px;
    font-weight: 600;
    color: #606266;
    .week {
      margin: 0 8px;
    }
  }
  .tips {
    color: #f56c6c;
    //margin-left: 26px;
  }
}
</style>
